package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.val;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 聪哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IFollowService followService;

    /**
     * 查多个
     * @param current
     * @return
     */
    @Override
    public Result queryHotBlog(Integer current) {
     //    根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.queryBlogUser(blog);
            // 查询点赞状态
            this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    /**
     * 根据id查博客笔记
     * @param id
     * @return
     */
    @Override
    public Result queryBlogById(Long id) {
        //1. 查询blog
        Blog blog = getById(id);
        if(blog==null){
            return Result.fail("博客不存在");
        }
        //2.查用户
        queryBlogUser(blog);

        //3. 查询点赞状态
        isBlogLiked(blog);

        return Result.ok(blog);
    }

    /**
     * 查询点赞状态
     * @param blog
     */
    private void isBlogLiked(Blog blog) {
        // 1.判断当前用户有没点赞
        UserDTO user = UserHolder.getUser();
        if(user == null){
            return;
        }
        Long userId = user.getId();
        // 2.查询点赞状态
        String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();
        Double score =  stringRedisTemplate.opsForZSet().score(key,userId.toString());
        blog.setIsLike(score != null);
    }

    /**
     * 点赞
     * @param id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {
        //1.判断当前用户有没点赞
        Long userId = UserHolder.getUser().getId();
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        Double score =  stringRedisTemplate.opsForZSet().score(key,userId.toString());
        if(score == null){
            //2.更新数据库信息 点赞+1
            boolean isSuccess =  update().setSql("liked = liked + 1").eq("id",id).update();
            //3. 保存用户到Redis的set集合
            if(isSuccess){
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
            }
        }else{
            //4. 点赞-1
            boolean isSuccess =  update().setSql("liked = liked - 1").eq("id",id).update();
            //5。 移除Redis
            if(isSuccess){
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }
        }
        return Result.ok();
    }

    /**
     * 查询点赞排行榜
     * @param id
     * @return
     */
    @Override
    public Result queryBlogLikes(Long id) {
        // 使用zrange查询TOP5
        Set<String> top5StrIds = stringRedisTemplate.opsForZSet().range(RedisConstants.BLOG_LIKED_KEY + id, 0, 4);
        if(top5StrIds==null || top5StrIds.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = top5StrIds.stream().map(Long::valueOf).collect(Collectors.toList());

        // 根据用户id查询数据库
        // 自定义sql查询
        List<User> users = userService.query().in("id", ids).last("ORDER BY FIELD(id," + StrUtil.join(",", ids) + ")").list();

        // DTO
        List<UserDTO> userDTOList = users
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());

        return Result.ok(userDTOList);
    }

    /**
     * 发布博客笔记
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        //1. 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        //2. 保存探店博文
        boolean isSuccess = save(blog);
        if(!isSuccess){
            return Result.fail("发布失败");
        }
        //3. 查询粉丝列表
        List<Follow> fansList = followService.query().eq("follow_user_id", user.getId()).list();

        //4. 将笔记发送到粉丝收件箱
        for (Follow fan : fansList) {
            Long userId = fan.getUserId();
            // 4.1 收件箱key
            String key = RedisConstants.FEED_KEY + userId;
            // 4.2 发送消息
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        return Result.ok(blog.getId());
    }

    /**
     * 滚动分页查询推送关注笔记
     * @param max
     * @param offset
     * @return
     */
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        // 1. 获取当前登录用户
        Long userId = UserHolder.getUser().getId();

        // 2. 获取收件箱信息 ----> 博客id、score（时间戳）
        String key = RedisConstants.FEED_KEY + userId;

        // 滚动分页查询 Z_REV_RANGE_BY_SCORE key min max LIMIT offset count
        Set<ZSetOperations.TypedTuple<String>> typedTuples =  stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key,0, max, offset, 3);

        // 非空判断
        if(typedTuples == null || typedTuples.isEmpty()){
            return Result.ok(Collections.emptyList());
        }

        // 3. 解析收件箱数据 blogId 、minTime、offset
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os = 1;
        for(ZSetOperations.TypedTuple<String> tuple : typedTuples){
            // 3.1 获取id
            String idStr = tuple.getValue();
            // 将id放到list集合
            ids.add(Long.valueOf(idStr));
            //3.2 获取分数
            long time = tuple.getScore().longValue();
            if(time == minTime){
                os++;
            }
            else{
                os=1;
                minTime = time;
            }
        }

        // 4. 根据id查询blog
        List<Blog> blogs = query().in("id",ids).last("ORDER BY FIELD(id," + StrUtil.join(",", ids) + ")").list();

        for(Blog blog : blogs){
            //4.2 查询blog相关的用户
            queryBlogUser(blog);
            //4.2 查询blog是否点赞
            isBlogLiked(blog);
        }

        //5. 封装返回
        ScrollResult r = new ScrollResult();
        r.setList(blogs);
        r.setOffset(os);
        r.setMinTime(minTime);

        return Result.ok(r);
    }

    /**
     * 复用方法封装
     * @param blog
     */
    private void queryBlogUser(Blog blog){
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

}
